import { randomString, isNull, BackendServices } from "mmb";
import {
  getAccountProxySafely,
  getMetadata,
  getOptionsOfLight,
  wrapperGrpcError,
} from "../grpc-client/grpcAdapter";
import * as config from "../conf/config.json"
import * as accountpb from "../grpc-client/proxy/account_pb";
import {SHA256, enc} from 'crypto-js';

export const checkMobile = async (mobile: string) => {
  const cl = getAccountProxySafely();
  const req = new accountpb.CheckMobileReq();

  req.setMobile(mobile);
  
  return new Promise((resolve, reject) => {
    cl.checkMobile(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      
      resolve(res.getIsexist());
    });
  });
}

export const register = async (mobile: string) => {
  const cl = getAccountProxySafely();
  const req = new accountpb.RegisterReq();
  
  req.setMobile(mobile)
  
  return new Promise((resolve, reject) => {
    cl.register(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      
      resolve(true);
    });
  });
}

export interface CredibleLoginParams {
  mobile: string;
  openId: string;
}

export const credibleLogin = async ({mobile, openId }: CredibleLoginParams): Promise<string> => {
  const cl = getAccountProxySafely();
  const req = new accountpb.CredibleLoginReq();
  
  req.setMobile(mobile)
  req.setApp(BackendServices.BGAPI)
  req.setNonce(openId)

  // 签名规则 mobile 值 + email 值 + app 值 + nonce 值 + secret 值 =>  sha256 签名
  const raw = `${mobile}${BackendServices.BGAPI}${openId}${config.account.secret}`
  const sign = SHA256(raw).toString(enc.Hex)

  console.log('raw=>', raw)
  console.log('sign=>', sign)
  req.setSign(sign)

  return new Promise((resolve, reject) => {
    cl.credibleLogin(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      
      resolve(res.getToken());
    });
  });
}